package com.xjzd.std.concurrency;

public class ThreadWaitNotify {

    public static void main(String[] args) throws InterruptedException {
        // 线程在执行synchronized方法时，如果没有获取到锁，会进入到锁池中
        // wait：让获取synchronized锁资源的线程释放锁，进入锁池中（状态：BLOCKED，主动竞争锁）
        // notify：让获取synchronized锁资源的线程随机通知等待池中的线程，进入到锁池中（状态：WAITING，等待唤醒）
        // notifyAll：通知等待池中全部的线程

        Thread t1 = new Thread(ThreadWaitNotify::sync, "t1");
        Thread t2 = new Thread(ThreadWaitNotify::sync, "t2");
        t1.start();
        t2.start();

        Thread.sleep(12000);
        synchronized (ThreadWaitNotify.class) {
            // wait,notify,notifyAll必须在同一个锁对象中
            ThreadWaitNotify.class.notifyAll();
        }
    }

    public static synchronized void sync() {
        for (int i = 0; i < 10; i++) {
            try {
                if (i == 5) {
                    // static方法加synchronized锁的是当前类对象
                    ThreadWaitNotify.class.wait();
                }
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
